﻿using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using DemoApp2.Models;
using System.Web.Security;
using Newtonsoft.Json.Linq;
using DemoApp2.Common;
using DemoApp2.Common;
using DemoApp2.Models;

namespace DemoApp2.Controllers
{
    public class AccountController : BaseController
    {
        public ActionResult Login()
        {
            string returnUrl = null;
            var urlReferrer = HttpContext.Request.UrlReferrer;
            if (urlReferrer != null)
            {
                returnUrl = urlReferrer.ToString();
            }
            else
            {
                returnUrl = "/";
            }

            var cookie = new HttpCookie(AppConfig.ClientReturnUrlCookieName, returnUrl);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            string authorizationServerAddress = string.Format("{0}{1}?client_id={2}&redirect_uri={3}&response_type={4}", AppConfig.AuthorizationServerBaseAddress, AppConfig.AuthorizePath, AppConfig.ClientId, AppConfig.RedirectUri, AppConfig.ResponseType);
            return Redirect(authorizationServerAddress);
        }

       
                    /// <summary>
        /// After login from OAuth Server, will be redirected to here
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult LoginRedirect(string code)
        {
            // Get AccessToken
            RestClientHelp restClientHelp = new RestClientHelp(AppConfig.AuthorizationServerBaseAddress, AppConfig.TokenPath);
            string accessTokenReuslt = restClientHelp.AccessToken(AppConfig.ClientId, AppConfig.ClientSecret, code);

            if (!string.IsNullOrEmpty(accessTokenReuslt))
            {
                dynamic contentForAccessToken = JObject.Parse(accessTokenReuslt);
                string accessToken = contentForAccessToken.access_token;
                string refreshToken = contentForAccessToken.refresh_token;

                // Get Refreshed AccessToken by RefreshToken, for subsequent Ajax request
                string refreshTokenResult = restClientHelp.RefreshToken(AppConfig.ClientId, AppConfig.ClientSecret, refreshToken);

                if (!string.IsNullOrEmpty(refreshTokenResult))
                {
                    dynamic contentForRefreshToken = JObject.Parse(refreshTokenResult);
                    string refreshedAccessToken = contentForRefreshToken.access_token;

                    // Set Refreshed AccessToken Cookie
                    var refreshedAccessTokenTicket = new FormsAuthenticationTicket(1, "UserName", DateTime.Now, DateTime.Now, false, refreshedAccessToken);
                    var encryptedRefreshedAccessTokenTicket = FormsAuthentication.Encrypt(refreshedAccessTokenTicket);
                    var refreshedAccessTokenCookie = new HttpCookie(AppConfig.RefreshedAccessTokenCookieName, encryptedRefreshedAccessTokenTicket);
                    refreshedAccessTokenCookie.HttpOnly = true;
                    System.Web.HttpContext.Current.Response.Cookies.Add(refreshedAccessTokenCookie);
                }

                // Set AccessToken Cookie
                var accessTokenTicket = new FormsAuthenticationTicket(1, "UserName", DateTime.Now, DateTime.Now, false, accessToken);
                var encryptedAccessTokenTicket = FormsAuthentication.Encrypt(accessTokenTicket);
                var accessTokenCookie = new HttpCookie(AppConfig.AccessTokenCookieName, encryptedAccessTokenTicket);
                accessTokenCookie.HttpOnly = true;
                System.Web.HttpContext.Current.Response.Cookies.Add(accessTokenCookie);

                string returnUrl = null;

                HttpCookie ClientReturnUrlCookie = HttpContext.Request.Cookies[AppConfig.ClientReturnUrlCookieName];
                if (ClientReturnUrlCookie != null)
                {
                    // Remove return URL cookie
                    ClientReturnUrlCookie.Expires = DateTime.Now.AddDays(-1);
                    HttpContext.Response.Cookies.Add(ClientReturnUrlCookie);

                    returnUrl = !string.IsNullOrEmpty(ClientReturnUrlCookie.Value) ? ClientReturnUrlCookie.Value : "/";
                }
                else
                {
                    returnUrl = "/";
                }

                // Redirect to the 'ReturnUrl' Page
                return Redirect(returnUrl);
            }

            return View();
        }

        public ActionResult Logout()
        {
            string returnUrl = null;

            var urlReferrer = HttpContext.Request.UrlReferrer;
            if (urlReferrer != null)
            {
                returnUrl = HttpContext.Request.UrlReferrer.ToString();
            }
            else
            {
                returnUrl = "/";
            }

            // After Logout, remove RefreshedAccessToken Cookie
            HttpCookie refreshedAccessTokenCookie = HttpContext.Request.Cookies[AppConfig.RefreshedAccessTokenCookieName];
            if (refreshedAccessTokenCookie != null)
            {
                refreshedAccessTokenCookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Response.Cookies.Add(refreshedAccessTokenCookie);
            }

            //Redirect to OAuth Server's logout action
            return Redirect(string.Format("{0}{1}?ReturnUrl={2}", AppConfig.AuthorizationServerBaseAddress, AppConfig.LogoutPath, returnUrl));
        }
        
    }
}